package uk.co.accolade.clash.app.intellij.toolwindow;

import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.peer.PeerFactory;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import uk.co.accolade.clash.app.ClashTree;

import javax.swing.*;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;

public class ClashToolWindow {

    private static final String WINDOW_ID = "Clash";

    private Project project;
    private ToolWindow toolWindow;
    private ClashTree clashTree;

    public ClashToolWindow( Project project ) {
        this.project = project;
    }

    public void init() {
        Application application = ApplicationManager.getApplication();
        ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);

        JPanel windowPanel = new JPanel(new BorderLayout());
        DefaultTreeCellRenderer renderer = new ClashIconRenderer( project, application, LocalFileSystem.getInstance() );

        clashTree = ClashTree.createTree( JumpToFile.createInstance( project ), renderer );
        windowPanel.add(clashTree.getTree(), BorderLayout.CENTER);

        toolWindow = toolWindowManager.registerToolWindow( WINDOW_ID, false, ToolWindowAnchor.BOTTOM );
        ContentFactory contentFactory = PeerFactory.getInstance().getContentFactory();
        Content content = contentFactory.createContent(windowPanel, "Clashes", false);
        toolWindow.getContentManager().addContent(content);
    }

    public void alertClash() {
        toolWindow.setTitle( "There's a clash" );
    }

    public void deregister() {
        ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
        toolWindowManager.unregisterToolWindow(WINDOW_ID);
    }

    public ClashTree getClashTree() {
        return clashTree;
    }
}
